package cn.wolfcode.wolf2w.resolver;

import cn.wolfcode.wolf2w.cache.service.IUserInfoRedisService;
import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.permission.UserParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;

public class UserInfoArgumentResolver implements HandlerMethodArgumentResolver {

    @Autowired
    private IUserInfoRedisService userInfoRedisService;
   //表示当前解析器可以解析哪种类型参数
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {


        return  methodParameter.getParameterType()==UserInfo.class&&methodParameter.hasParameterAnnotation(UserParam.class);
    }

    //执行解析逻辑,并注入参数,必须是supportsParameter 方法返回true
    @Override
    public Object resolveArgument(MethodParameter methodParameter,
                                  ModelAndViewContainer modelAndViewContainer,
                                  NativeWebRequest nativeWebRequest,
                                  WebDataBinderFactory webDataBinderFactory) throws Exception {
        //获取登录对象
        HttpServletRequest req = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
        String token = req.getHeader("token");
        //返回值是请求映射方法声明形式参数声明的UserInfo对象的值
        return userInfoRedisService.getUserByToken(token);
    }
}
